<?php
// "Manage groups from my phone" page for your customers, on your own address.
// Upload this file as index.php into a new folder on any website (another domain is fine), for example
// https://yourtvsite.com/tv/  -  then type that address in the panel: Menu sections > Manage groups from a phone > Phone page address.
// It passes the page through from your panel, so customers never see your panel address.
$PANEL = '__PANEL__';   // your panel (filled in when you downloaded this file)

$qs = (string)($_SERVER['QUERY_STRING'] ?? '');
$url = rtrim($PANEL, '/') . '/api/control.php' . ($qs !== '' ? '?' . $qs : '');
$post = ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST';
$send = ['X-TM-Proxy: 1', 'X-Forwarded-For: ' . (string)($_SERVER['REMOTE_ADDR'] ?? '')];
$body = false; $code = 502; $type = 'text/html; charset=utf-8';
if (function_exists('curl_init')) {
    $c = curl_init($url);
    curl_setopt_array($c, [CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 25, CURLOPT_HTTPHEADER => $send, CURLOPT_USERAGENT => 'TivimateAIO-PhonePage']);
    if ($post) { curl_setopt($c, CURLOPT_POST, true); curl_setopt($c, CURLOPT_POSTFIELDS, http_build_query($_POST)); }
    $body = curl_exec($c);
    $code = (int)curl_getinfo($c, CURLINFO_RESPONSE_CODE);
    $type = (string)curl_getinfo($c, CURLINFO_CONTENT_TYPE);
    curl_close($c);
} else {
    $head = $send; $head[] = 'User-Agent: TivimateAIO-PhonePage'; if ($post) $head[] = 'Content-Type: application/x-www-form-urlencoded';
    $ctx = stream_context_create(['http' => ['method' => $post ? 'POST' : 'GET', 'header' => implode("\r\n", $head), 'content' => $post ? http_build_query($_POST) : '', 'timeout' => 25, 'ignore_errors' => true]]);
    $body = @file_get_contents($url, false, $ctx);
    foreach ($http_response_header ?? [] as $l) {
        if (preg_match('#^HTTP/\S+\s+(\d{3})#', $l, $m)) $code = (int)$m[1];
        elseif (stripos($l, 'Content-Type:') === 0) $type = trim(substr($l, 13));
    }
}
if (!is_string($body) || $code < 200) { http_response_code(502); header('Content-Type: text/plain; charset=utf-8'); exit('This page is not available right now. Please try again in a moment.'); }
http_response_code($code);
header('Content-Type: ' . ($type !== '' ? $type : 'text/html; charset=utf-8'));
header('Cache-Control: no-store');
header('Referrer-Policy: no-referrer');
echo $body;
